package com.cyh.nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.FileChannel;

/**
 * 读文件内容
 * */
public class BufferDemo01 {

    public static void main(String[] args) throws Exception {
        RandomAccessFile aFile = new RandomAccessFile("D:\\cyh\\work_java\\TestNioOrIo\\src\\com\\cyh\\1.txt", "rw");
        FileChannel channel = aFile.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);

        //将数据写入buffer
        int bytesRead = channel.read(buffer);

        while (bytesRead != -1) {
            //切换模式，读取buffer
            buffer.flip();
            while (buffer.hasRemaining()) {
                System.out.println((char)buffer.get());
            }

            //清空，模式变成写入模式
            buffer.clear();
            bytesRead = channel.read(buffer);
        }

        aFile.close();
    }
}
